<!-- 户室号匹配组件（新） -->
<template>
  <div>
    <div class="d-flex">
      <div class="flex-1 cell-item">{{ portVO.portType | getPortTypeName }}</div>
      <!-- 匹配小区 -->
      <div class="flex-1 cell-item" v-loading="portVO.loading">
        <div v-show="!portVO.portResblockName && !portVO.loading" class="text-red">
          未匹配
        </div>
        <div v-show="portVO.portResblockName && !portVO.loading">
          {{ portVO.portResblockName }}
        </div>
      </div>

      <!-- 匹配 户室号 -->
      <div class="flex-3 cell-item" v-loading="portVO.hallRoomLoading">
        <div
          v-show="!portVO.hallRoomLoading && portVO.hallRoomNumber.length == 0 && portVO.portResblockName"
          style="margin: auto"
          class="fs-sm text-center"
        >
          加载失败,
          <el-button type="text" @click="handleRetryColumn">点击重试</el-button>
        </div>
        <div class="d-flex">
          <template v-for="item in portVO.hallRoomNumber">
            <!-- 分两种情况 一种是自定义输入 另一种只能点选 -->
            <el-input
              v-if="portVO.huShiHao"
              v-model="portVO[item.key]"
              :key="item.key"
              style="margin: 0 5px"
              :class="{ 'reject-input': !portVO[item.key] }"
              :placeholder="item.title"
            ></el-input>
            <el-select
              v-else
              v-model="portVO[item.key]"
              filterable
              remote
              :allow-create="portVO.huShiHao"
              :placeholder="item.title"
              :key="item.key"
              :loading="portVO.singleLoading"
              :disabled="selectDisabled(item.key)"
              :remote-method="remoteMethod(item.key)"
              @focus="handleFocusHsh('portVO', item.key)"
              @change="handleChangeHsh('portVO', $event)"
              style="margin: 0 5px"
              :class="{ 'reject-input': !portVO[item.key] }"
            >
              <el-option
                v-for="item in portVO.buildUnitDoorOptions"
                :label="item.portBuild || item.portUnit || item.portDoorNum"
                :value="item.platformBuildId || item.platformUnitId || item.platformDoorNumId"
                :key="item.platformBuildId || item.platformUnitId || item.platformDoorNumId"
              ></el-option>
            </el-select>
          </template>
        </div>
        <div :class="[hushihaoFilledPrue ? 'text-green' : 'text-red', 'text-center']">
          {{ hshTips }}
        </div>
      </div>

      <!-- 总价 -->
      <div class="flex-1 cell-item">
        <el-input v-model="myTotalPrices" :disabled="!resblockMached">
        </el-input>
      </div>
      <!-- 面积 -->
      <div class="flex-1 cell-item">
        <el-input v-model="publishSize" :readonly="portVO.isMatchingBuild" :disabled="!resblockMached" @focus="initializeSize=false"> </el-input>
      </div>
      <!-- 均价 -->
      <div class="flex-1 cell-item">{{ averagePrice }}</div>
      <!-- 操作 -->
      <div class="flex-1 cell-item">
        <el-button size="mini" type="text" @click="handlePopShow">{{
          portVO.portResblockName ? '更换小区' : '手工匹配小区'
        }}</el-button>
      </div>

      <!-- 手动匹配弹层 -->
      <el-dialog
        :visible.sync="popVisible"
        top="30vh"
        :close-on-click-modal="false"
        :show-close="true"
        width="600px"
        append-to-body
      >
        <span slot="title" class="d-flex ai-baseline">
          <span class="fs-xl" style="margin-left: 8px">手工匹配</span>
          <span>（注：输入小区或关键字后，需点击“搜索”按钮）</span>
        </span>
        <ComManualMatch :popModel="popModel" :delId="delId"></ComManualMatch>
        <span slot="footer" class="dialog-footer">
          <el-button plain @click="popVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePopConfirm">确认</el-button>
        </span>
      </el-dialog>
    </div>
    <div class="tips">
      <span>备注：安居客参考均价{{ avgUnitPrice > 0 ? avgUnitPrice / 10000 + '万/㎡' : '未查到' }} </span>
      <!-- <span v-if="myBuildSize > 0">{{ portVO.buildSizeLocked ? '🔒' : '🔑' }} {{ myBuildSize + '㎡' }}</span> -->
    </div>
  </div>
</template>

<script>
import comTitleItem from '@/views/house/com/com-title-item';
import ComManualMatch from '@/views/house/com/com-manual-match.vue';
import { hallRoomNumber } from '@/config/house/houseDetailConfig';
import { matchingResblock, matchingBuild, matchingUnit, matchinDoorNum, queryAjkPriceInfoList, getException } from '@/api/user';
import { debounce } from '@/utils/utilsNew';
import { PORT_CODE_AJK } from '@/config/house/platform';

export default {
  name: 'ComMatchItem',
  components: {
    comTitleItem,
    ComManualMatch,
  },
  props: {
    model: {
      type: Object,
      default() {
        return {};
      }
    },
    resblockName: {
      type: String,
      default: '',
    },
    noPortAccount: {
      type: Number,
      default: 0,
    },
    delId: String,
    autoMatch: Boolean,
  },
  data() {
    return {
      popModel: this.$store.getters['houseInfo/getManualAreaModel'](PORT_CODE_AJK),

      initializeSize: true, // 面积首次不触发（0.03的）校验

      myTotalPrices: '',
      myBuildSize: '',
      publishSize: '', //发布面积 用户手动输入在页面展示的

      popVisible: false,

      avgUnitPrice: '', //安居客的参考价格

      // 端口信息
      portVO: {
        portResblockName: '', //端口小区名称
        portBuild: '', //栋/幢
        portUnit: '', //单元/号
        portDoorNum: '', //门牌

        platformResblockId: '', //平台小区id   (platform 代表安居客等平台)
        platformBuildId: '', //平台楼栋id
        platformUnitId: '', //平台单元ID
        platformDoorNumId: '', //平台门牌号ID

        portType: '', // 平台类型
        loading: false, //匹配小区加载。。。
        hallRoomLoading: false, //户室号加载。。。
        singleLoading: false, //单个户室号加载。。。
        isMatchingBuild: false, //匹配面积中。。。
        searchKey: '', //搜索关键词
        hallRoomNumber,

        housingEstateOptions: [], //匹配小区选项
        buildUnitDoorOptions: [], //户室号的选项
        huShiHao: false, //是否支持手动输入
        buildSizeLocked: false, //是否面积锁定

        totalPrice: '',
        buildingSize: '',
        publishSize: '',
      },
    };
  },

  created() {
    this.buildSizeRenewal = debounce(this.buildSizeRenewal.bind(this), 1000);
  },

  mounted() {
    const { model } = this
    this.myTotalPrices = model.totalPrice;
    this.myBuildSize = model.buildingSize;
    this.publishSize = model.publishSize || model.buildingSize;

    this.renderPort(model, this.resblockName);
  },

  computed: {
    // 户室号匹配文案
    hshTips({portVO, hushihaoFilledPrue}) {
      if (!portVO.portResblockName) return '(未匹配)';
      if (hushihaoFilledPrue) return '(已匹配)';
      return `(未匹配 - ${portVO.huShiHao ? '请输入户室号' : '请选择户室号'})`;
    },
    resblockMached({ portVO }) {
      return portVO.portResblockName && portVO.platformResblockId;
    },
    averagePrice() {
      if (!this.myTotalPrices || !this.publishSize) return '';
      const p = (this.myTotalPrices / this.publishSize).toFixed(2);
      return p;
    },

    // 纯 户室号有没有填
    hushihaoFilledPrue() {
      let info = this.portVO;
      if (!info.portResblockName) return false;
      if (!info.hallRoomNumber || info.hallRoomNumber.length == 0) {
        return false;
      }
      const protFilledList = hallRoomNumber.map((v) => v.key).filter((key) => this.isValidValue(info[key]));
      let r = protFilledList.length >= info.hallRoomNumber.length;
      return r;
    },

    selectDisabled() {
      return (key) => {
        if (this.portVO.hallRoomNumber.length == 0) {
          return true;
        }
        if (!this.portVO.portResblockName) return true;

        let hasBuild = this.portVO.hallRoomNumber.find((v) => v.key == 'portBuild');
        let hasUnit = this.portVO.hallRoomNumber.find((v) => v.key == 'portUnit');

        if (key == 'portUnit') {
          if (hasBuild && !this.portVO.portBuild) return true;
          return false;
        }
        if (key == 'portDoorNum') {
          if (hasBuild && !this.portVO.portBuild) return true;
          if (hasUnit && !this.portVO.portUnit) return true;
          return false;
        }
      };
    },
  },

  watch: {
    portVO: {
      handler(newVal) {
        this.$emit('updateportvo', newVal);
      },
      deep: true,
    },

    'portVO.platformResblockId'(id) {
      this.getAjkPriceInfo(id);
      this.$bus.$emit('info:recommendUpdate');
    },

    myBuildSize(newValue, oldValue) {
      if (newValue == oldValue) return;
      this.portVO.buildingSize = newValue;
    },

    myTotalPrices(newValue, oldValue) {
      if (newValue == oldValue) return;
      this.portVO.totalPrice = newValue;
    },

    publishSize(newValue, oldValue) {
      if (newValue == oldValue) return;
      this.portVO.publishSize = newValue;

      this.buildSizeRenewal(newValue);
    },
  },

  beforeDestroy() {},

  methods: {
    buildSizeRenewal(publishSize) {
      if (!publishSize) return;
      
      const { myBuildSize } = this;
      // 户室号填充前
      if (!this.hushihaoFilledPrue) {
        this.$bus.$emit('info:recommendUpdate');

        // 户室号面积已锁定
      } else if (this.portVO.buildSizeLocked) {
        if (this.initializeSize) return;
        
        if (Math.abs(publishSize - myBuildSize) / myBuildSize > 0.03) {
          this.clearHsh('portVO');
          this.$bus.$emit('info:recommendUpdate');
        }
      }
    },
    getAjkPriceInfo(id) {
      if (this.noPortAccount != 1) return;
      
      queryAjkPriceInfoList({ portResblockIdList: [id], delId: this.delId }).then(({ content }) => {
        if (content && content.length) {
          this.avgUnitPrice = content[0].avgUnitPrice;
        }
      });
    },
    renderPort(data, resblockName) {
      Object.assign(this.portVO, data);

      this.$bus.$emit('info:recommendUpdate');

      // 可推表示填写完整了
      if (data.onePushFlag == 0) {
        this.portVO.hallRoomNumber = hallRoomNumber.filter((v) => !!data[v.key]);

      } else {
        this.resetHuShiHao("portVO");

        // 已匹配过小区
        if (data.portResblockName) {
          this.getHshColumn("portVO", data);

          // 自动帮他匹配小区
        } else {
          if (this.noPortAccount == 1) {
            this.portVO.hallRoomNumber = [];
            // console.log('组件', this.autoMatch);
            
            if (this.autoMatch) {
              this.autoMatchingResblock("portVO", resblockName);
            }
          }
        }
      }
    },

    // 更新为推荐的户室号
    updateRecommendHushihao(info) {
      if (
        this.portVO.loading ||
        this.portVO.hallRoomLoading ||
        this.portVO.singleLoading ||
        this.portVO.isMatchingBuild
      ) {
        return this.$message.error('加载中，请稍后再试~');
      }
      // console.log("更新为推荐的户室号，", info);

      const keys = ['buildingName', 'buildingUnitName', 'houseName'];
      const arr = hallRoomNumber.filter((item, i) => info[keys[i]]);
      this.portVO.hallRoomNumber = arr;
      this.portVO.huShiHao = false;

      this.portVO.platformBuildId = info.buildingId;
      this.portVO.platformUnitId = info.buildingUnitId;
      this.portVO.platformDoorNumId = info.houseId;

      this.portVO.portDoorNumId = info.houseId;

      this.portVO.portBuild = info.buildingName;
      this.portVO.portUnit = info.buildingUnitName;
      this.portVO.portDoorNum = info.houseName;

      this.myBuildSize = info.buildingArea;

      this.portVO.buildSizeLocked = info.buildingAreaLock == '0';
    },

    // 自动匹配小区
    autoMatchingResblock(way, name) {
      const m = this[way];
      m.loading = true;
      matchingResblock({
        delId: this.delId,
        portResblockName: (name || '').trim(),
        portType: m.portType,
        actionType: way == 'portVO' ? 0 : 1,
        type: 0,
      })
        .then((content) => {
          m.loading = false;

          if (content.length) {
            m.housingEstateOptions = content;
            if (way == 'portVO') {
              this.handleChangePortResblockName(way, content[0].portResblockName);
            }
          }
        })
        .catch(() => {
          m.loading = false;
        });
    },

    // 匹配到小区
    handleChangePortResblockName(way, value) {
      const m = this[way];
      const item = m.housingEstateOptions.find((v) => v.portResblockName == value);
      Object.assign(m, item);

      if (way == 'portVO') {
        this.getHshColumn(way, item);
      }
    },

    handleFocusHsh(way, key, kw = '') {
      const m = this[way];
      if (m.huShiHao) return;

      m.singleLoading = true;
      m.buildUnitDoorOptions = [];
      const ct = () => {
        // 需要尝试重新请求
        m.singleLoading = false;
      };

      const cb = (content) => {
        m.singleLoading = false;

        if (content.length) {
          m.buildUnitDoorOptions = content;
        }
      };

      if (key == 'portBuild') {
        matchingBuild({
          delId: this.delId,
          portResblockId: m.portResblockId,
          portType: m.portType,
          type: 0,
          platformResblockId: m.platformResblockId,
          kw,
        })
          .then(cb)
          .catch(ct);
      } else if (key == 'portUnit') {
        matchingUnit({
          delId: this.delId,
          portResblockId: m.portResblockId,
          portType: m.portType,
          portBuildId: m.portBuildId,
          platformResblockId: m.platformResblockId,
          platformBuildId: m.platformBuildId,
          kw,
        })
          .then(cb)
          .catch(ct);
      } else if (key == 'portDoorNum') {
        matchinDoorNum({
          delId: this.delId,
          portResblockId: m.portResblockId,
          portBuildId: m.portBuildId,
          portUnitId: m.portUnitId,
          portType: m.portType,
          platformResblockId: m.platformResblockId,
          platformBuildId: m.platformBuildId,
          platformUnitId: m.platformUnitId,
          kw,
        })
          .then(cb)
          .catch(ct);
      }
    },

    handleChangeHsh(way, id) {
      const m = this[way];
      let key = '';
      let item = m.buildUnitDoorOptions.find((v) => {
        if (v.platformBuildId == id) {
          key = 'platformBuildId';
          return true;
        } else if (v.platformUnitId == id) {
          key = 'platformUnitId';
          return true;
        } else if (v.platformDoorNumId == id) {
          key = 'platformDoorNumId';
          return true;
        }
      });

      if (key == 'platformBuildId') {
        m.portUnit = '';
        m.portUnitId = '';
        m.platformUnitId = '';
        m.portDoorNum = '';
        m.portDoorNumId = '';
        m.platformDoorNumId = '';
      } else if (key == 'platformUnitId') {
        m.portDoorNum = '';
        m.portDoorNumId = '';
        m.platformDoorNumId = '';
      }

      Object.assign(m, item);
      const arr = ['portBuild', 'portUnit', 'portDoorNum'].filter((v) => !!this.portVO[v]);
      if (arr.length >= this.portVO.hallRoomNumber.length) {
        this.verifyBuildSize();
      }
    },

    verifyBuildSize() {
      this.portVO.isMatchingBuild = true;

      matchingBuild({
        delId: this.delId,
        portResblockId: this.portVO.portResblockId,
        portType: this.portVO.portType,
        type: 1,
        platformResblockId: this.portVO.platformResblockId,
        portDoorNumId: this.portVO.portDoorNumId,
        platformDoorNumId: this.portVO.platformDoorNumId,
      })
        .then((content) => {
          this.portVO.isMatchingBuild = false;

          let obj = JSON.parse(content);
          if (obj.attr && obj.attr.mianJi && obj.attr.mianJi.value) {
            let buildSize = obj.attr.mianJi.value;
            // this.$message.info('当前已帮您匹配到该房源的面积，此时面积不可修改');
            this.myBuildSize = buildSize;
            this.portVO.buildSizeLocked = true;
          } else {
            this.portVO.buildSizeLocked = false;
          }
        })
        .catch(() => {
          this.portVO.buildSizeLocked = false;
        });
    },

    // 获取某小区的户室号栏目数
    getHshColumn(way, info) {
      const m = this[way];
      m.huShiHao = false;
      m.buildUnitDoorOptions = [];

      m.hallRoomLoading = true;
      this.resetHuShiHao(way);

      if (m.hallRoomNumber.length) {
        m.hallRoomNumber = [];
      }

      return matchingBuild({
        delId: this.delId,
        portResblockId: info.portResblockId,
        portType: m.portType,
        type: 1,
        platformResblockId: info.platformResblockId,
      })
        .then((content) => {
          // 成功查询到
          m.hallRoomLoading = false;
          if (content == '{}') {
            return;
          }
          let data = JSON.parse(content);

          const keys = ['isShowBuilding', 'isShowUnit', 'isShowHouse'];
          const arr = hallRoomNumber.filter((item, i) => data[keys[i]] == 1);
          m.hallRoomNumber = arr;

          m.huShiHao = data.huShiHao;
          // console.log("是否支持手动", data.huShiHao);

          // 手动输入则可以开始校验价格了
          if (data.huShiHao) {
            this.portVO.buildSizeLocked = false;
          }
        })
        .catch(() => {
          m.hallRoomLoading = false;
        });
    },

    // 重试户室号栏目
    handleRetryColumn() {
      this.getHshColumn('portVO', this.portVO);
    },

    resetHuShiHao(way) {
      const m = this[way];
      this.clearHsh(way);

      m.huShiHao = false;
    },

    clearHsh(way) {
      const m = this[way];
      m.portBuild = '';
      m.portUnit = '';
      m.portDoorNum = '';

      m.platformBuildId = '';
      m.platformUnitId = '';
      m.platformDoorNumId = '';
    },

    handlePopShow() {
      this.popVisible = true;

      this.popModel.searchKey = '';
      this.popModel.portResblockName = '';
      this.popModel.platformResblockId = '';
      this.popModel.housingEstateOptions = [];
    },

    handlePopConfirm() {
      if (this.popModel.platformResblockId) {
        this.portVO.platformResblockId = this.popModel.platformResblockId;
        this.portVO.portResblockName = this.popModel.portResblockName;

        this.getHshColumn('portVO', this.portVO);
        this.popVisible = false;
      } else {
        if (this.popModel.housingEstateOptions.length) {
          return this.$message.error('请选择弹窗中的选项匹配小区');
        }

        return this.$message.error('请输入小区或关键字后，点击搜索');
      }
    },

    remoteMethod(key) {
      return (query) => {
        if (!query) return;
        this.handleFocusHsh('portVO', key, query);
      };
    },
  },
};
</script>

<style scoped>
.reject-input >>> .el-input__inner {
  border-color: red;
}
.tips {
  position: absolute;
  font-size: 12px;
  font-weight: 500;
  color: #ef4d4d;
  bottom: -26px;
}
</style>
